package com.nd.android.musicboxlibrary.ui.jaymusicbox.search;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.common.utils.StarAppUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.adapter.JayMusicSearchAdapter;
import com.nd.android.musicboxlibrary.ui.adapter.JayMusicSearchSingleAdapter;
import com.nd.android.musicboxlibrary.ui.common.BaseFragmentActivity;
import com.nd.android.musicboxlibrary.ui.common.UnMixable;
import com.nd.android.musicboxlibrary.ui.common.ViewInjectorWithReflect;
import com.nd.android.musicboxlibrary.ui.view.CustomEditText;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.nd.android.musicboxlibrary.util.NdTask;
import com.squareup.otto.Subscribe;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * <br>
 * Created 2014年7月5日 下午4:11:54
 * 
 * @version
 * @author wat.ztag
 * 
 * @see
 */
public class JayMusicSearchActivity extends BaseFragmentActivity implements MagicNumber {

    /**
     * 
     * <br>Created 2014年11月28日 上午12:05:46
     * @author       wat.ztag
    */
    @Override
    public void initMagicNumber() {}
    
    private int lstSum;

    private static final String CLASS_NAME = "jay_search";

    private View loading;

    private List<MusicInfo> moreSingles = new ArrayList<MusicInfo>();

    @Override
    public void onResume() {
        super.onResume();
        BusProvider.getInstance().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        BusProvider.getInstance().unregister(this);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:34:19
     * 
     * @param event MenuPositionEvent
     * @author wat.ztag
     */
    @Subscribe
    public void selectionByPosition(MenuPositionEvent event) {
        int sum = ConfigHelper.getInstance(this).loadIntKey(
                ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, 0);
        if (sum < lstSum) {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
            } else if (holder.lst.getLastVisiblePosition() - 1 == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        } else {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        }
    }

    private ViewHolder holder = new ViewHolder();

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:34:36
     * 
     * @version JayMusicSearchActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class ViewHolder implements UnMixable {
        ListView lst;
        CustomEditText edtSearch;
        LinearLayout pnlSearchNull;
        TextView txtSearchNull, txtBack;
        ImageView ivSearch;
    }

    private JayMusicSearchSingleAdapter mSingleAdapter;

    private JayMusicSearchAdapter mSearchAdapter;

    private List<MusicInfo> singles = new ArrayList<MusicInfo>();

    private List<String> searchs = new ArrayList<String>();

    private Drawable right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mbx_jay_music_search_activity);
        ViewInjectorWithReflect.injectView(holder, this);
        initData();
        setupView();
        addListeners();
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:34:55
     * 
     * @author wat.ztag
     */
    protected void initData() {
        Type type = new TypeToken<List<String>>() {
        }.getType();
        String history = ConfigHelper.getInstance(this).loadKey(
                ConfigHelper.CONFIG_KEY_SEARCH_HISTORY);
        if (!TextUtils.isEmpty(history)) {
            searchs = new Gson().fromJson(history, type);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:35:47
     * 
     * @author wat.ztag
     */
    private void setupView() {

        loading = LayoutInflater.from(this).inflate(R.layout.mbx_jay_music_search_footer, null);

        mSingleAdapter = new JayMusicSearchSingleAdapter(this);
        mSingleAdapter.setDatas(singles);

        Drawable left = initDrawable(R.drawable.mbx_search);
        holder.edtSearch.setLeftDrawables(left);
        right = initDrawable(R.drawable.mbx_search_del);
        mSearchAdapter = new JayMusicSearchAdapter(this);
        mSearchAdapter.setDatas(searchs);
        holder.lst.setAdapter(mSearchAdapter);
        StarAppUtils.setViewTypeFace(holder.txtBack, false);
        StarAppUtils.setViewTypeFace(holder.txtSearchNull, false);
        StarAppUtils.setViewTypeFace((TextView)loading.findViewById(R.id.txtFooter), false);
        StarAppUtils.setViewTypeFace(holder.edtSearch, false);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:35:51
     * 
     * @author wat.ztag
     */
    private void addListeners() {
        holder.edtSearch.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_ENTER && arg2.getAction() == KeyEvent.ACTION_DOWN) {
                    if (getCurrentFocus() != null) {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                                .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                        InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    searhKey();
                }
                return false;
            }
        });
        addEditDrawableListener();
        holder.edtSearch.addTextChangedListener(new TextSearchWatcher());
        holder.lst.setOnItemClickListener(new SearchItemListener());
        holder.ivSearch.setOnClickListener(this);
        holder.txtBack.setOnClickListener(this);

        holder.lst.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
                lstSum = arg2;
                int sum = ConfigHelper.getInstance(getApplicationContext()).loadIntKey(
                        ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2 + 1);
                if (arg2 < sum && arg2 != 0) {
                    ConfigHelper.getInstance(getApplicationContext()).saveIntKey(
                            ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2);
                }
            }
        });
        loading.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                holder.lst.removeFooterView(loading);
                mSingleAdapter.setDatas(moreSingles, true);
            }
        });
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:36:18
     * 
     * @version JayMusicSearchActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class SearchItemListener implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String strSearch = mSearchAdapter.getDatas().get(arg2);
            holder.edtSearch.setText(strSearch);
            saveHistory(strSearch);
            if (getCurrentFocus() != null) {
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
            }
            new SearchMusicList(JayMusicSearchActivity.this, R.string.mbx_runing)
                    .executeByVersion(strSearch);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:36:23
     * 
     * @param strSearch String
     * @author wat.ztag
     */
    private void initSearchNullView(String strSearch) {
        holder.pnlSearchNull.setVisibility(View.VISIBLE);
        holder.txtSearchNull.setText(getString(R.string.mbx_jaymusic_search_null, strSearch));
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:36:29
     * 
     * @author wat.ztag
     */
    private void hideSearchNullView() {
        holder.pnlSearchNull.setVisibility(View.GONE);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:38:43
     * 
     * @param search String
     * @author wat.ztag
     */
    private void saveHistory(String search) {
        initData();
        Iterator ite = searchs.iterator();
        while (ite.hasNext()) {
            String o = (String) ite.next();
            if (o.equals(search)) {
                ite.remove();
            }
        }
        searchs.add(0, search);
        if (searchs.size() > n30) {
            searchs.remove(n30);
        }
        String history = new Gson().toJson(searchs);
        ConfigHelper.getInstance(this).saveKey(ConfigHelper.CONFIG_KEY_SEARCH_HISTORY, history);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:38:56
     * 
     * @author wat.ztag
     */
    private void searhKey() {
        mSingleAdapter.getState().clear();
        String search = holder.edtSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(search)) {
            saveHistory(search);
            // InputMethodManager imm = (InputMethodManager)
            // getSystemService(Context.INPUT_METHOD_SERVICE);
            // if (imm.isActive()) {
            // imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
            // InputMethodManager.HIDE_NOT_ALWAYS);
            // }
            new SearchMusicList(JayMusicSearchActivity.this, R.string.mbx_runing)
                    .executeByVersion(search);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:39:00
     * 
     * @param drawableId int
     * @return Drawable
     * @author wat.ztag
     */
    private Drawable initDrawable(int drawableId) {
        Drawable drawable = getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        return drawable;
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:39:03
     * 
     * @author wat.ztag
     */
    private void addEditDrawableListener() {
        holder.edtSearch.setDrawableClickListener(new CustomEditText.DrawableClickListener() {
            @Override
            public void onClick(DrawablePosition target) {
                switch (target) {
                case RIGHT:
                    holder.edtSearch.setText("");
                    holder.edtSearch.setRightDrawables(null);
                    holder.lst.removeFooterView(loading);
                    holder.lst.setAdapter(mSearchAdapter);
                    holder.lst.setOnItemClickListener(new SearchItemListener());
                    initData();
                    mSearchAdapter.setDatas(searchs);
                    hideSearchNullView();
                    break;

                default:
                    break;
                }
            }
        });
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:39:09
     * 
     * @version JayMusicSearchActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class TextSearchWatcher implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            String inputQuery = s.toString().trim();
            if (inputQuery.length() < 1) {
                holder.edtSearch.setRightDrawables(null);
                holder.lst.removeFooterView(loading);
                holder.lst.setAdapter(mSearchAdapter);
                holder.lst.setOnItemClickListener(new SearchItemListener());
                initData();
                mSearchAdapter.setDatas(searchs);
                hideSearchNullView();
                return;
            } else {
                holder.edtSearch.setRightDrawables(right);
                String str = MusicBoxUtils.stringFilter(inputQuery);
                if (!inputQuery.equals(str)) {
                    holder.edtSearch.setText(str);
                    holder.edtSearch.setSelection(str.length());
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:39:21
     * 
     * @version JayMusicSearchActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class SearchMusicList extends NdTask {

        private String strSearch;

        /**
         * Creates a new instance of SearchMusicList. <br>
         * Created 2014年9月11日 下午11:39:25
         * 
         * @param context Context
         * @param resId int
         */
        public SearchMusicList(Context context, int resId) {
            super(context, resId);
        }

        @Override
        protected void doSuccess(Object result) {
            if (result != null) {
                singles = (List<MusicInfo>) result;
                int size = singles.size();
                if (size > n30) {
                    moreSingles.clear();
                    for (int i = n30; i < size; i++) {
                        moreSingles.add(singles.get(i));
                    }
                    singles.removeAll(moreSingles);
                    holder.lst.addFooterView(loading);
                    holder.lst.setAdapter(mSingleAdapter);
                    mSingleAdapter.setDatas(singles);
                    holder.lst.setOnItemClickListener(mSingleAdapter);
                } else {
                    holder.lst.setAdapter(mSingleAdapter);
                    mSingleAdapter.setDatas(singles);
                    holder.lst.setOnItemClickListener(mSingleAdapter);
                    if (size == 0) {
                        initSearchNullView(strSearch);
                    } else {
                        hideSearchNullView();
                    }
                }
            } else {
                initSearchNullView(strSearch);
            }
        }

        @Override
        protected void doFail(NdException result) {
            Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();
            initSearchNullView(strSearch);
        }

        @Override
        protected Object doInBackground(Object... arg0) {
            strSearch = (String) arg0[0];
            return ManagerFactory.getPlaylistInstance(getApplicationContext()).searchMusicList(
                    strSearch);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.ivSearch) {
            searhKey();

        } else if (id == R.id.txtBack) {
            this.finish();

        }

        super.onClick(v);
    }
}
